package reentrantlcok;

import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : ZhuQi
 * @version : 时间:2022/7/29 14:03 版本:
 *
 * 测试 ReentrantLock 的使用
 */
public class demo1 {

    /**
     * 测试内容: 测试 ReentrantLock 的使用
     * 测试结果: 共享数据能够成功锁住
     */
    @Test
    public void should_synchronize_calc_I_increments_with_reentrant() throws Exception {
        ReentrantLock lock = new ReentrantLock();
        ThreadGroup defaultGroup = new ThreadGroup("default");
        final HashMap<String, Integer> map = new HashMap<>();
        for (int i = 0; i < 100; i++) {
            Thread thread = new Thread(defaultGroup, () -> {
                try {
                    lock.lock();
                    if (map.containsKey("key")) {
                        map.put("key", map.get("key") + 1);
                    } else {
                        map.put("key", 1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    System.out.print(Thread.currentThread().getName() + "判断当前线程持有锁的次数:" + lock.getHoldCount() + "--");
                    System.out.println(Thread.currentThread().getName() + "当前等待此锁的线程:" + lock.getQueueLength());
                    lock.unlock();
                }
            }, "线程");
            thread.start();
            boolean b = lock.hasQueuedThread(thread);
            System.out.println(thread.getName() + "判断当前线程是否在排队等锁:" + b);
        }
        while (defaultGroup.activeCount() != 0) {
            TimeUnit.SECONDS.sleep(1);
        }
        System.out.println(map);
    }

    @Test
    public void test01() throws Exception {

    }
}
